package com.tim.app.ui.activity.selected;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventListener;
import com.application.library.runtime.event.EventManager;
import com.application.library.widget.EmptyLayout;
import com.application.library.widget.loadmore.LoadMoreContainer;
import com.application.library.widget.loadmore.LoadMoreHandler;
import com.application.library.widget.loadmore.LoadMoreRecycleViewContainer;
import com.application.library.widget.recycle.BaseRecyclerAdapter;
import com.application.library.widget.recycle.HorizontalDividerItemDecoration;
import com.application.library.widget.recycle.WrapRecyclerView;
import com.application.library.widget.refresh.PtrClassicFrameLayout;
import com.application.library.widget.refresh.PtrFrameLayout;
import com.application.library.widget.refresh.PtrHandler;
import com.google.gson.Gson;
import com.tim.app.R;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.server.api.API_Found;
import com.tim.app.server.api.API_Statistics;
import com.tim.app.server.entry.Answer;
import com.tim.app.server.entry.Problem;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.net.ServerAddressManager;
import com.tim.app.server.result.ProblemAnswerResult;
import com.tim.app.server.result.ProblemDetailResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.share.CustomShareBoard;
import com.tim.app.ui.activity.BaseActivity;
import com.tim.app.ui.activity.EmptyActivity;
import com.tim.app.ui.adapter.selceted.AnswerAdapter;
import com.tim.app.ui.view.QuestionAndAnswerHeadView;
import com.tim.app.util.ToastUtil;
import com.tim.app.util.ViewGT;

import java.util.ArrayList;
import java.util.List;

import static com.tim.app.constant.AppKey.REQUEST_CODE_PROBLEM_ANSWER;


/**
 * 问答详情页面
 */
public class QuestionAndAnswerDetailActivity extends BaseActivity implements PtrHandler, LoadMoreHandler, BaseRecyclerAdapter.OnItemClickListener {

    public static final String TAG = "QuestionAndAnswerDetailActivity";
    private Problem problem;
    private boolean isFromPush = false;
    private boolean isSort = false;

    private int pageNumber = 1;//页码

    private ImageButton ibBack;
    private ImageButton ibMore;
    private RelativeLayout rlBottomContainer;
    private TextView tvGotoAnswer;

    private PtrClassicFrameLayout refresh_layout;
    private LoadMoreRecycleViewContainer load_more;
    private WrapRecyclerView wrvAnswer;
    private QuestionAndAnswerHeadView headView;
    private EmptyLayout emptyLayout;
    private AnswerAdapter adapter;
    private List<Answer> dataList;

    public static void start(Context context, Problem data, boolean isFromPush) {
        Intent intent = new Intent(context, QuestionAndAnswerDetailActivity.class);
        intent.putExtra(AppKey.PROBLEM, data);
        intent.putExtra(AppKey.IS_FROM_PUSH, isFromPush);
        if (isFromPush) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_question_and_answer_detail;
    }


    @Override
    public void initView() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        ibBack = (ImageButton) findViewById(R.id.ibBack);
        ibMore = (ImageButton) findViewById(R.id.ibMore);
        tvGotoAnswer = (TextView) findViewById(R.id.tvGotoAnswer);
        rlBottomContainer = (RelativeLayout) findViewById(R.id.rlBottomContainer);

        refresh_layout = (PtrClassicFrameLayout) findViewById(R.id.refresh_layout);
        load_more = (LoadMoreRecycleViewContainer) findViewById(R.id.load_more);
        wrvAnswer = (WrapRecyclerView) findViewById(R.id.wrvAnswer);
        headView = (QuestionAndAnswerHeadView) LayoutInflater.from(this).inflate(R.layout.question_and_answer_head_view, load_more, false);

        wrvAnswer.setOverScrollMode(View.OVER_SCROLL_NEVER);
        emptyLayout = new EmptyLayout(this, refresh_layout);
        emptyLayout.showLoading();
        emptyLayout.setEmptyDrawable(R.drawable.ic_empty_search);
        emptyLayout.setEmptyText("该内容已经被删除了", "");

        refresh_layout.disableWhenHorizontalMove(true);
        refresh_layout.setPtrHandler(this);
        load_more.useDefaultFooter(View.GONE);
        load_more.setAutoLoadMore(true);
        load_more.setLoadMoreHandler(this);

//        emptyLayout.setEmptyButtonClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                emptyLayout.showLoading();
//                pageNumber = 1;
//                API_Found.ins().getProblemDetailInfo(TAG, problem.getId(), detailCallback);
//                API_Found.ins().getProblemAnswerInfo(TAG, problem.getId(), pageNumber, AppKey.PAGE_SIZE, isSort, refreshCallback);
//            }
//        });

        ibBack.setOnClickListener(this);
        ibMore.setOnClickListener(this);

        tvGotoAnswer.setOnClickListener(this);
        rlBottomContainer.setOnClickListener(this);

        if (dataList == null) {
            dataList = new ArrayList<>();
        }

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        wrvAnswer.setLayoutManager(layoutManager);
        adapter = new AnswerAdapter(this, dataList);
        adapter.setOnItemClickListener(this);
        wrvAnswer.setAdapter(adapter);
        wrvAnswer.addHeaderView(headView);
        wrvAnswer.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this).color(getResources().getColor(R.color.view_background_color)).size((int) getResources().getDimension(R.dimen.dimen_5)).build());

        problem = (Problem) getIntent().getSerializableExtra(AppKey.PROBLEM);
        isFromPush = getIntent().getBooleanExtra(AppKey.IS_FROM_PUSH, false);
        EventManager.ins().registListener(EventTag.ORDER_BY_TIME, eventListener);
        EventManager.ins().registListener(EventTag.ORDER_BY_QUALITY, eventListener);
        EventManager.ins().registListener(EventTag.DO_REPORT, eventListener);
        EventManager.ins().registListener(EventTag.DO_EDIT_PROBLEM, eventListener);
        EventManager.ins().registListener(EventTag.DO_CONTENT_DELETE, eventListener);
        EventManager.ins().registListener(EventTag.ON_ANSWER_DELETED, eventListener);
        EventManager.ins().registListener(EventTag.ON_ANSWER_ADD, eventListener);
        EventManager.ins().registListener(EventTag.ON_PROBLEM_EDIT, eventListener);
    }

    EventListener eventListener = new EventListener() {
        @Override
        public void handleMessage(int what, int arg1, int arg2, Object dataobj) {
            switch (what) {
                case EventTag.ORDER_BY_TIME:
                    isSort = false;
                    refreshAnswerList();
                    break;
                case EventTag.ORDER_BY_QUALITY:
                    isSort = true;
                    refreshAnswerList();
                    break;
                case EventTag.DO_REPORT:
                    if (UserManager.ins().isLogin()) {
                        UserManager.ins().report(TAG, AppKey.TYPE_PROBLEM, problem.getId());
                    } else {
                        ViewGT.gotoLoginActivity(QuestionAndAnswerDetailActivity.this);
                    }
                    break;
                case EventTag.DO_EDIT_PROBLEM:
                    AskQuestionActivity.startWithEditProblem(QuestionAndAnswerDetailActivity.this, problem);
                    break;
                case EventTag.DO_CONTENT_DELETE:
                    CustomShareBoard.ShareFrom shareFrom = (CustomShareBoard.ShareFrom) dataobj;
                    if (shareFrom == CustomShareBoard.ShareFrom.QUESTION) {
                        API_Found.ins().deleteProblem(TAG, problem.getId(), new StringResponseCallback() {
                            @Override
                            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                                if (errCode == ResponseResult.ResultStatus.OK) {
                                    EventManager.ins().sendEvent(EventTag.ON_QUESTION_DELETED, 0, 0, problem.getId());
                                    ToastUtil.showToast("删除成功");
                                    finish();
                                } else {
                                    ToastUtil.showToast(errMsg);
                                }
                                return false;
                            }
                        });
                    }
                    break;
                case EventTag.ON_PROBLEM_EDIT:
                case EventTag.ON_ANSWER_ADD:
                    initData();
                    break;
                case EventTag.ON_ANSWER_DELETED:
                    String prbolemId = String.valueOf(arg1);
                    if (prbolemId.equals(problem.getId())) {
                        updateAnswerState();
                    }
                    String deleteId = (String) dataobj;
                    for (int i = 0; i < dataList.size(); i++) {
                        if (dataList.get(i).getId().equals(deleteId)) {
                            dataList.remove(i);
                            adapter.notifyDataSetChanged();
                            break;
                        }
                    }
                    break;
            }
        }
    };

    /**
     * 重新请求answer
     */
    private void refreshAnswerList() {
        pageNumber = 1;
        API_Found.ins().getProblemAnswerInfo(TAG, problem.getId(), pageNumber, AppKey.PAGE_SIZE, isSort, refreshCallback);
    }

    @Override
    public void initData() {
        pageNumber = 1;
        API_Found.ins().getProblemDetailInfo(TAG, problem.getId(), detailCallback);
        API_Found.ins().getProblemAnswerInfo(TAG, problem.getId(), pageNumber, AppKey.PAGE_SIZE, false, refreshCallback);
        UserManager.ins().addBrowserHistory(TAG, AppKey.TYPE_PROBLEM, problem.getId());
        API_Statistics.ins().addDetailData(TAG, this, AppKey.TYPE_PROBLEM, problem.getId());
    }

    StringResponseCallback detailCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                ProblemDetailResult result = new Gson().fromJson(resultValue, ProblemDetailResult.class);

                if (null != result && null != result.getRes() && null != result.getRes().getProblem()) {
                    emptyLayout.showContent();
                    problem = result.getRes().getProblem();
                    headView.setContentUrl(problem.getContentUrl());
                    updateUi(problem);
                }
            } else if (errCode == ResponseResult.ResultStatus.DELETED) {
                emptyLayout.showEmpty();
                EmptyActivity.start(QuestionAndAnswerDetailActivity.this);
                finish();
            } else {
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };

    StringResponseCallback refreshCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK) {
                if (resultValue != null) {
                    ProblemAnswerResult result = new Gson().fromJson(resultValue, ProblemAnswerResult.class);

                    if (null != result && null != result.getRes()) {
                        problem.setAnswerCount(result.getTotal());
                        headView.refreshAnswerCount(problem.getAnswerCount());
                        dataList.clear();
                        if (null != result && null != result.getRes() && null != result.getRes().getArraylist() && null != result.getRes().getArraylist().getResult()) {
                            pageNumber = result.getRes().getArraylist().getCurrentPageNo();
                            dataList.addAll(result.getRes().getArraylist().getResult());
                        }
                        adapter.notifyDataSetChanged();
                        if (result.getRes().getArraylist().getCurrentPageNo() != result.getRes().getArraylist().getTotalPageCount()) {
                            load_more.loadMoreFinish(false, true);
                        } else {
                            load_more.loadMoreFinish(false, false);
                        }

                    } else {
                        load_more.loadMoreFinish(false, false);
                    }
                }
            } else {
                load_more.loadMoreFinish(false, false);
            }
            return false;
        }
    };

    StringResponseCallback moreCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                ProblemAnswerResult result = new Gson().fromJson(resultValue, ProblemAnswerResult.class);

                if (null != result && null != result.getRes()) {
                    if (null != result && null != result.getRes() && null != result.getRes().getArraylist() && null != result.getRes().getArraylist().getResult()) {
                        dataList.addAll(result.getRes().getArraylist().getResult());
                        pageNumber = result.getRes().getArraylist().getCurrentPageNo();
                    }
                    adapter.notifyDataSetChanged();
                    if (result.getRes().getArraylist().getCurrentPageNo() != result.getRes().getArraylist().getTotalPageCount()) {
                        load_more.loadMoreFinish(false, true);
                    } else {
                        load_more.loadMoreFinish(false, false);
                    }
                } else {
                    load_more.loadMoreFinish(false, false);
                }

            } else {
                load_more.loadMoreFinish(false, false);
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };

    private boolean isAnswered = false;

    private void updateUi(Problem data) {
        headView.setData(data);
        if (null != data.getActionStateMsg().getAnswerState()) {
            isAnswered = true;
            tvGotoAnswer.setText(getString(R.string.lookatMyAnswer));
        }
    }


    private void updateAnswerState() {
        isAnswered = false;
        tvGotoAnswer.setText("回答");
        if (problem.getActionStateMsg() != null) {
            problem.getActionStateMsg().setAnswerState(null);
        }
        problem.setAnswerCount(problem.getAnswerCount() - 1);
        headView.updateAnswerCount(problem);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        EventManager.ins().removeListener(EventTag.ORDER_BY_TIME, eventListener);
        EventManager.ins().removeListener(EventTag.ORDER_BY_QUALITY, eventListener);
        EventManager.ins().removeListener(EventTag.DO_REPORT, eventListener);
        EventManager.ins().removeListener(EventTag.DO_CONTENT_DELETE, eventListener);
        EventManager.ins().removeListener(EventTag.DO_EDIT_PROBLEM, eventListener);
        EventManager.ins().removeListener(EventTag.ON_ANSWER_DELETED, eventListener);
        EventManager.ins().removeListener(EventTag.ON_ANSWER_ADD, eventListener);
        EventManager.ins().removeListener(EventTag.ON_PROBLEM_EDIT, eventListener);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (RESULT_OK == resultCode) {
            switch (requestCode) {
                case AppKey.REQUEST_CODE_PROBLEM_ANSWER:
                    refreshAnswerList();
                    break;
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ibBack:
                onBackPressed();
                break;
            case R.id.ibMore:
                CustomShareBoard shareBoard;
                String targetUrl = problem.getShareUrl();
                if (UserManager.ins().isLogin() && !TextUtils.isEmpty(problem.getUserId())) {
                    if (problem.getUserId().equals(UserManager.ins().getUserId())) {
                        shareBoard = new CustomShareBoard(this, CustomShareBoard.ShareFrom.QUESTION);
                        if (problem.getAnswerCount() == 0) {
                            shareBoard.setDelete(true);
                            shareBoard.setEidt(true, true);
                        } else {
                            shareBoard.setEidt(true, false);
                        }
                    } else {
                        shareBoard = new CustomShareBoard(this, CustomShareBoard.ShareFrom.NORMAL);
                    }
                } else {
                    shareBoard = new CustomShareBoard(this, CustomShareBoard.ShareFrom.NORMAL);
                }

                String imageUrl = ServerAddressManager.SHARE_DEFAULT_LOGO_URL;
                if (null != problem.getImageUrl() && problem.getImageUrl().size() > 0) {
                    imageUrl = problem.getImageUrl().get(0);
                }
                String title = problem.getTitle() + " - " + problem.getAnswerCount() + "个回答," + problem.getConcernCount() + "人关注";
                String sinaDesc = title + problem.getShareUrl() + " (解答情感问题，下载@茉莉社区 APP)";
                shareBoard.setShareInfo(title, problem.getDigest(), sinaDesc, imageUrl, imageUrl, targetUrl);
                shareBoard.showPopup(false);
                break;
            case R.id.rlBottomContainer:
            case R.id.tvGotoAnswer:
                if (!UserManager.ins().isLogin()) {
                    ViewGT.gotoLoginActivity(this);
                    return;
                }
                if (isAnswered) {
                    Answer answer = new Answer();
                    answer.setId(String.valueOf(problem.getActionStateMsg().getAnswerState().intValue()));
                    AnswerDetailActivity.start(this, answer, false);
                } else {
                    Intent intentAnswer = new Intent(QuestionAndAnswerDetailActivity.this, AnswerActivity.class);
                    intentAnswer.putExtra(AppKey.IS_ANSWER, true);
                    intentAnswer.putExtra(AppKey.QUESTION_ID, problem.getId());
                    startActivityForResult(intentAnswer, REQUEST_CODE_PROBLEM_ANSWER);
                }
                break;
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public void onBackPressed() {
        if (isFromPush) {
            ViewGT.gotoMainActivity(QuestionAndAnswerDetailActivity.this);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onLoadMore(LoadMoreContainer loadMoreContainer) {
        API_Found.ins().getProblemAnswerInfo(TAG, problem.getId(), pageNumber + 1, AppKey.PAGE_SIZE, isSort, moreCallback);
    }

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return false;
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {

    }


    @Override
    public void onItemClick(View view, int position, long id) {
        Answer answer = dataList.get(position);
        answer.setProblemId(problem.getId());
        answer.setProblemTitle(problem.getTitle());
        AnswerDetailActivity.start(this, answer, false);
    }
}
